<?php
class Silk_Mapi_ProductController extends Silk_Mapi_Controller_Action {
    protected $_productCollection;

    public function IndexAction() {
        echo "OK";
    }

    private function _getSession() {
        return Mage::getSingleton('customer/session');  
    }

    public function getCustomer() {
        return $this->_getSession()->getCustomer();
    }

    /**
     * Initialize requested category object
     *
     * @return Mage_Catalog_Model_Category
     */
    protected function _initCatagory()
    {
        Mage::dispatchEvent('catalog_controller_category_init_before', array('controller_action' => $this));
        $categoryId = (int) $this->getRequest()->getParam('category_id', false);
        if (!$categoryId) {
            return false;
        }

        $category = Mage::getModel('catalog/category')
            ->setStoreId(Mage::app()->getStore()->getId())
            ->load($categoryId);

        if (!Mage::helper('catalog/category')->canShow($category)) {
            return false;
        }
        Mage::getSingleton('catalog/session')->setLastVisitedCategoryId($category->getId());
        Mage::register('current_category', $category);
        Mage::register('current_entity_key', $category->getPath());

        try {
            Mage::dispatchEvent(
                'catalog_controller_category_init_after',
                array(
                    'category' => $category,
                    'controller_action' => $this
                )
            );
        } catch (Mage_Core_Exception $e) {
            Mage::logException($e);
            return false;
        }

        return $category;
    }

    public function listAction()
    {
        $sort = $this->getRequest()->getParam('sort','desc');
        $sort = $sort=='desc'?'asc':'desc';
        $this->getRequest()->setParam('dir', $sort);

        $_page = $this->getRequest()->getParam('page', 1);
        $_categoryId = $this->getRequest()->getParam('category_id');
        $_keyword = $this->getRequest()->getParam('keyword');
        $_brand = $this->getRequest()->getParam('brand');
        $callback = $this->getRequest()->getParam('callback');
        $storeId = Mage::app()->getStore()->getId();
        if(!$_categoryId) $_categoryId = 12;


        if($_categoryId == 100)
        {
            $_imageHelper = Mage::helper('catalog/image');
            $_customer = $this->getCustomer();
            $_orders = Mage::getModel('sales/order')->getCollection()
                ->addFieldToFilter('customer_id', array('eq'=>$_customer->getId()))
                ->setOrder('entity_id')->setPage(1,3);
            $collection = array();
            $ids = array();
            foreach($_orders as $_order)
            {
                //$ids = array();
                $_items = $_order->getItemsCollection();
                foreach($_items as $item)
                {
                    $ids[] = $item->getProductId();
                }
            }

            $collection = Mage::getModel("catalog/product")->getCollection()
                ->addAttributeToSelect('*')
                ->addWebsiteFilter(Mage::app()->getWebsite())
                ->addAttributeToFilter('entity_id', array('in'=>$ids));

            $data = array();
            foreach($collection as $item)
            {
                $_product = $item;
                $products[] = array(
                    'id'=>$_product->getId(),
                    'name'=>$_product->getName(),
                    'price'=>$_product->getPrice(),
                    'special_price'=>$_product->getFinalPrice(),
                    'image'=>$_imageHelper->init($_product, 'small_image')->resize(250)."",
                    'promotion'=>$_product->getPromotion(),
                    'tag'=>$_product->getAttributeText('tag')
                );
            }
            $data['page'] = 1;
            $data['total'] = $collection->getSize();
            $data['totalPage'] = 1;
            $data['products'] = $products;
            $data['brands'] = array();
            $this->render($data);
            return;
        } else if ($_categoryId == 14) {
            $_imageHelper = Mage::helper('catalog/image');
            $store = Mage::app()->getStore();
            $collection = Mage::getModel('catalog/product')->getCollection()->setStoreId($store->getId())
                ->addWebsiteFilter($store->getWebsiteId())
                ->addAttributeToSelect('*')
                ->addAttributeToFilter('tag', Silk_Qslb_Helper_Tag::EXPLOSION)
                ->setOrder('tag_position', 'desc');

            Mage::getSingleton('catalog/product_status')->addSaleableFilterToCollection($collection);
            Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($collection);
            Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($collection);

            $data = array();
            foreach ($collection as $item) {
                $_product = $item;
                $products[] = array(
                    'id' => $_product->getId(),
                    'name' => $_product->getName(),
                    'price' => $_product->getPrice(),
                    'special_price' => $_product->getFinalPrice(),
                    'image' => $_imageHelper->init($_product, 'small_image')->resize(250) . "",
                    'promotion' => $_product->getPromotion(),
                    'tag' => $_product->getAttributeText('tag')
                );
            }
            $data['page'] = 1;
            $data['total'] = $collection->getSize();
            $data['totalPage'] = 1;
            $data['products'] = $products;
            $data['brands'] = array();
            $this->render($data);
            return;
        }
        else
        {
            //使用GET参数来缓存数据
            //wap  站可能要增加storeid
            $getData = $_GET;
            unset($getData['token']);
            $paramsKey = md5(json_encode($getData)).$storeId;
            $json = apc_fetch($paramsKey);
            if($json)
            {
                if($callback)
                {
                    echo "{$callback}({$json})";
                }
                else
                {
                    echo $json;
                }
                return;
            }

            $response = $this->getResponse();
            $response->setHeader('Content-type', 'application/json');
            $this->_initCatagory();
            $this->loadLayout();
            $this->renderLayout();
        }
    }

    public function viewAction()
    {
    	$_imageHelper = Mage::helper('catalog/image');
        $_checkoutHelper = Mage::helper('checkout');
    	$productId = $this->getRequest()->getParam('id');
    	if(!$productId)
    	{
    		$this->render("商品不存在");
    		return;
    	}
    	$product = Mage::getModel('catalog/product')->load($productId);
    	if(!$product || !$product->getId())
    	{
    		$this->render("没有这件商品");
    		return;
    	}

    	$data = array();
    	$data['id'] = $product->getId();
    	$data['name'] = $product->getName();

        $data['price'] = $product->getPrice();
        $data['final_price'] = $product->getFinalPrice();
    	$data['image'] = $_imageHelper->init($product,'small_image')->resize(500)."";
    	$images = array();
    	$gallery = $product->getMediaGalleryImages();
    	foreach($gallery as $image)
    	{
    		$images[] = $image->getUrl();
    	}
        if($images)
        {
            $data['images'] = $images;
        }
        else
        {
            $data['images'] = array($_imageHelper->init($product,'small_image')->resize(500)."");
        }
    	
        $description = $product->getShortDescription();
        $description = Mage::helper('cms')->getBlockTemplateProcessor()->filter($description);
    	$data['description'] = $description;
        $data['promotion'] = $product->getPromotion();
        $data['tag'] = $product->getAttributeText('tag');

        $data['related'] = array();
        $relateds = Mage::getModel('catalog/product')->getCollection()
            ->addAttributeToFilter('brand', $product->getBrand())
            ->addWebsiteFilter(Mage::app()->getWebsite())
            ->addAttributeToFilter('status', 1)
            ->addAttributeToFilter('visibility', 4)
            ->setPage(1,4);

        foreach($relateds as $_product)
        {
            $_product->load($_product->getId());
            $item = array();
            $item['id'] = $_product->getId();
            $item['name'] = $_product->getName();

            $item['price'] = $_product->getPrice();
            $item['final_price'] = $_product->getFinalPrice();
            $item['image'] = $_imageHelper->init($_product,'small_image')->resize(500)."";
            $description = $_product->getShortDescription();
            $description = Mage::helper('cms')->getBlockTemplateProcessor()->filter($description);
            $item['description'] = $description;
            $item['promotion'] = $_product->getPromotion();
            $item['tag'] = $_product->getAttributeText('tag');
            $data['related'][] = $item;
        }
        
    	$this->render($data);
    }

}